package photostock.view;

import java.util.Collections;
import java.util.Comparator;
import java.util.ResourceBundle;
import java.util.Vector;

import org.jdom.DocType;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.filter.ContentFilter;
import org.jdom.filter.ElementFilter;

import photostock.model.Album;
import photostock.model.Photo;
import photostock.model.User;
import photostock.model.UserItem;

public class WidgetFactory {

	private static ResourceBundle resource = ResourceBundle.getBundle(WidgetFactory.class.getName());
	private static final String JS = "text/javascript";
	private static final String CSS = "text/css";
	
	public static WebPage getDefaultPage() {
		
		Document defaultPage = new Document(new Widget("html"), new DocType("html", "-//W3C//DTD XHTML 1.0 Transitional//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"));
		
		
		Element headerImg = new Element("img");
		headerImg.setAttribute("src", "images/site/head.png");
		Element headerFond = new Widget("div", "header", "headerFond");
		headerFond.setContent(headerImg);
		
		Element headerMenu = new Widget("div", "header", "headerMenu");
		Element headerUser = new Widget("div", "header", "headerUser");
		
		Element header = new Widget("div", "header", "header");
		header.addContent(headerFond);
		header.addContent(headerMenu);
		header.addContent(headerUser);
		
		Element contentMenu = new Widget("div", "content", "contentMenu");
		
		Element floatingForm = new Widget("div", "form", "floatingForm");
		floatingForm.setContent(getRegisterForm());
		Element uploadIFrame = new Widget("div", "iframe", "uploadIFrame");		
		Element contentMain = new Widget("div", "content", "contentMain");
		
		Element content = new Widget("div", "content", "content");
		content.addContent(contentMenu);
		content.addContent(contentMain);
		
		Element footerImg = new Element("img");
		footerImg.setAttribute("src", "/Photostock/images/site/bottom.png");
		Element footerFond = new Widget("div", "footer", "footerFond");
		footerFond.setContent(footerImg);
		Element footerMenu = new Widget("div", "footer", "footerMenu");
		Element footer = new Widget("div", "footer", "footer");
		footer.addContent(footerFond);
		footer.addContent(footerMenu);
		
		Element body = new Widget("body");
		body.addContent(header);
		body.addContent(content);
		body.addContent(floatingForm);
		body.addContent(uploadIFrame);
		body.addContent(footer);
		
		Widget customedCss = new Widget("link", "cssLink", "customedCss");
		customedCss.setAttribute("href", "/Photostock/css/default.css");
		customedCss.setAttribute("rel", "stylesheet");
		customedCss.setAttribute("type", "text/css");
		
		
		Element head = new Widget("head");
		head.addContent(getScript("general"));
		head.addContent(getScript("user"));
		head.addContent(getScript("album"));
		head.addContent(getStyle("general"));
		head.addContent(customedCss);
		
		
		
		 defaultPage.getRootElement().addContent(head);
		defaultPage.getRootElement().addContent(body);
		return new WebPage((Document)defaultPage.clone());
	}
	

    public static ResourceBundle getResources() {
    	return resource;
    }
    
	
	public static void initUser(WebPage page, User user) {
		page.getElement("headerUser").removeContent();
		if (!user.isLogged()) {
			page.getElement("headerUser").setContent(getLoginForm());
			page.getElement("floatingForm").setContent(getRegisterForm());
		} else {
			page.getElement("headerUser").setContent(getLoginConf(user.getName()));
		}
	}

	public static void initAlbum(WebPage page, User user, Album album) {
		page.getElement("contentMain").removeContent();
		if (user.isLogged()) {
			if (user.getChildrenItems().size() > 0) {
				if (null != album) page.getElement("contentMain").setContent(getAlbum(album));
				else page.getElement("contentMain").setContent(getAlbumSet(user.getChildrenItems()));
				
			} else {
				page.getElement("contentMain").setContent(new Widget("p").setText("pas encore d'album ..."));
			}
		} else {
			page.getElement("contentMain").setContent(getAlbum(new Album()));
		}
	}

	
	public static Widget getLoginForm() {
		
		FormWidget form = new FormWidget("headerUser", "ajaxLog(this.form, 'login');");
		form.setImage("/Photostock/images/site/user.png");
		form.addLabel(resource.getString("loginLabel"));
		form.addText("login", "ajaxCheckPseudo(this.form, 'checkLoginPseudo');");

		form.addLabel(resource.getString("passwordLabel"));
		form.addPassword("password", "");
		form.addValidButton(resource.getString("valider"));
		form.addContent(getLink(resource.getString("subscribe"), "link", "registerLink", "showRegister()"));
		return form;	
	}

	public static Widget getRegisterForm() {

		FormWidget form = new FormWidget("contentMain", "ajaxRegister(this.form, 'register');");
		form.setImage("/Photostock/images/site/inscription.png");
		form.addLabel(resource.getString("loginLabel"));
		form.addText("login", "ajaxCheckPseudo(this.form, 'checkLoginPseudo');");
		form.addLabel(resource.getString("passwordLabel"));
		form.addPassword("password", "");
		form.addLabel(resource.getString("acceptMailLabel"));
		form.addCheckbox("check", "acceptMail(this);");
		form.addLabel(resource.getString("mailAdresseLabel"));
		form.addText("mailAdresse", "ajaxCheckMail(this.form, 'checkMail');");
		form.addValidButton(resource.getString("valider"));
		form.addButton(resource.getString("annuler"), "cancelForm('contentMainForm');");

		return form;
	}

	
	public static Widget getLoginConf(String s) {
		FormWidget form = new FormWidget("headerUserValid", "ajaxLog(this.form, 'login');");
		form.setImage("/Photostock/images/site/user.png");
		form.addLabel(resource.getString("welcome") + " " + s);
		form.addButton(resource.getString("disconnect"), "ajaxDisconnect(this);");
		return form;
	}
	
	
	public static Element getAlbumSet(Vector<UserItem> items) {
		Widget albumSet = new Widget("div", "albumSet", "albumSet");
		for (UserItem item : items) {
			albumSet.addContent(getAlbumLink(item));			
		}
		return albumSet;
	}
	
	public static Element getAlbumLink(UserItem item) {
		((Album)item).initChildrenItems();
		Element link = getLink("", "albumLink", "album"+item.getId(), "setDocStyle('"+((Album)item).getSkin()+"');ajaxAlbumDetail('"+item.getId()+"', 'ajaxAlbumDetail');");
		link.addContent(getSmallGallery(item.getChildrenItems()));
		link.addContent(new Widget("label").setText(item.getName()));
		return link;
	}
	
	public static Element getAlbum(UserItem item) {
		return new AlbumWidget(item);		
	}
	
	public static Element getSmallGallery(Vector<UserItem> items) {
		System.out.println("in small gallery : " + items.size());
		Widget table = new Widget("table", "smallGallery", "smallGallery");
		Widget row = new Widget("tr");
		for (int i=0; i<4; i++) {
			System.out.println("in boucle");
			if (i%2 == 0) {
				table.addContent(row);
				row = new Widget("tr");
			}
			Widget cell = new Widget("td");
			Widget image;
			if (i < items.size()) {
				image = new Widget("img", "mini", ""+i);
				image.setAttribute("src", ((Photo)items.elementAt(i)).toMin().getWebPath());
				cell.setContent(image);
			} else {
				image = new Widget("img", "mini", "fake"+i);
				image.setAttribute("src", "/Photostock/images/site/empty.gif");
				cell.setContent(image);
			}
			row.addContent(cell);
		}
		table.addContent(row);		
		System.out.println(table);
		return table;
	}
	
	
	public static Element getGallery(Vector<UserItem> items) {
		Widget gallery = new Widget("table", "galleryTable", "galleryTable");
		Widget row = new Widget("tr");
		for (int i=0; i<9; i++) {
			if (i%3 == 0) {
				gallery.addContent(row);
				row = new Widget("tr");
			}
			Widget cell = new Widget("td");
			Widget image;
			if (i < items.size()) {
				image = new Widget("img", "miniature", ""+i);
				image.setAttribute("src", ((Photo)items.elementAt(i)).toMin().getWebPath());
				Element link = getLink("", "photoLink", ""+i, "ajaxImageFocus('"+i+"', 'imageFocus');");
				link.setContent(image);
				cell.setContent(link);
			} else {
				image = new Widget("img", "miniature", "fake"+i);
				image.setAttribute("src", "/Photostock/images/site/empty.gif");
				cell.setContent(image);
			}
			
			row.addContent(cell);
		}
		gallery.addContent(row);
		return gallery;
	}
	
	public static Element getFocused(UserItem item) {
		Widget focused = new Widget("img", "focused", "focusedImg"+item.getId());
		focused.setAttribute("src", ((Photo)item).toMax().getWebPath());
		return focused;
	}
	
	public static Widget getScript(String s) {
		Widget script = new Widget("script");
		script.setAttribute("type", JS);
		script.setAttribute("src", "/Photostock/js/" + s + ".js");
		script.setText("");
		return script;	
	}

	public static void addScript(WebPage page, String s) {
		page.getHead().addContent(getScript(s));
		sort(page.getHead());
	}

	public static Widget getStyle(String s) {
		Widget script = new Widget("style");
		script.setAttribute("type", CSS);
		script.setText("@import url(/Photostock/css/" + s + ".css);");
		return script;	
	}

	public static void addStyle(WebPage page, String s) {
		page.getHead().addContent(getStyle(s));
		sort(page.getHead());
	}
	
	public static Element getLink(String value, String cl, String id, String script) {
		Widget link = new Widget("a", cl, id);
		link.setAttribute("href", "#");
		link.setAttribute("onclick", script);
		link.setText(value);
		return link;
	}
	
	public static void initMenu(WebPage page, String type) {
		page.getElement("headerMenu").setContent(getTopMenu(type));                                    
		page.getElement("contentMenu").setContent(getSideMenu(type));  
		page.getElement("footerMenu").setContent(getBottomMenu(type));                                    
	}
	
	
	public static Widget getTopMenu(String s) {
		Widget menu = new Widget("ul", s+"Menu", s+"TopMenu");
		for (String item : resource.getString(s+"TopMenu").split(",")) {
			Widget listItem = new Widget("li", s+"MenuItem", item);
			listItem.setContent(getLink(resource.getString(item), s+"Link", s+"Link"+item, "ajax"+item+"()"));
			menu.addContent(listItem);
		}
		return menu;
	}
	
	public static Widget getSideMenu(String s) {
		Widget menu = new Widget("ul", s+"Menu", s+"SideMenu");
		for (String item : resource.getString(s+"SideMenu").split(",")) {
			Widget listItem = new Widget("li", s+"MenuItem", item);
			listItem.setContent(getLink(resource.getString(item), s+"Link", s+"Link"+item, "ajax"+item+"()"));
			menu.addContent(listItem);
		}
		return menu;
	}

	public static Widget getBottomMenu(String s) {
		Widget menu = new Widget("ul", s+"Menu", s+"BottomMenu");
		for (String item : resource.getString(s+"BottomMenu").split(",")) {
			Widget listItem = new Widget("li", s+"MenuItem", item);
			listItem.setContent(getLink(resource.getString(item), s+"Link", s+"Link"+item, "ajax"+item+"()"));
			menu.addContent(listItem);
		}
		return menu;
	}
	
	
	public static void sort(Element e) {
		Vector<Element> vector = new Vector<Element>();
		for (Object o : e.getContent(new ContentFilter(ContentFilter.ELEMENT))) {
			vector.add((Element)o);
		}
		e.removeContent();
		Collections.sort(vector, new ElementComparator());
		e.setContent(vector);
	}
	
	public static IdFilter getIdFilter(String s) {
		return new IdFilter(s);
	}
	
	static class ElementComparator implements Comparator<Element> {
		public int compare(Element e1, Element e2) {
			return e1.getName().compareTo(e2.getName());
		}
	}
	
	static class IdFilter extends ElementFilter {
		private static final long serialVersionUID = 20090501L;
		private String id;
		
		public IdFilter(String s) {
			id = s;
		}
		public boolean matches(Object o) {
			if (o instanceof Element) {
				Element e = (Element)o;
				return (e.getAttribute("id") != null && e.getAttribute("id").getValue().equals(id)); 
			}
			return false;
		}
		
	}
	
	static class StyleFilter extends ElementFilter {
		private static final long serialVersionUID = 20090501L;
		private String style;
		
		public StyleFilter(String s) {
			style = s;
		}
		public boolean matches(Object o) {
			if (o instanceof Element) {
				Element e = (Element)o;
				return (e.getText() != null && e.getText().indexOf(style) != -1); 
			}
			return false;
		}
		
	}

}
